using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace MyPhotoIndex.ImageCache
{
    class WorkerStream : IDisposable
    {
        Semaphore m_semaphore;
        FileStream m_stream;
        List<WorkerStream> m_workerStreams;

        public WorkerStream(String path, List<WorkerStream> workerStreams, Semaphore semaphore)
        {
            m_stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            if (m_stream.Length == 0)
            {
                BinaryWriter writer = new BinaryWriter(m_stream);
                writer.Write((int)0);
            }
            m_semaphore = semaphore;
            m_workerStreams = workerStreams;
        }

        public FileStream Stream
        {
            get
            {
                return m_stream;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            lock (m_workerStreams)
            {
                m_workerStreams.Add(this);
            }

            m_semaphore.Release();
        }

        #endregion
    }
}
